// 共享的商品数据存储层
// 实际项目中这应该连接到数据库

export interface Product {
  id: number;
  name: string;
  price: number;
  description: string;
  category: string;
  stock: number;
  createTime: string;
  updateTime?: string;
}

// 模拟商品数据存储
let products: Product[] = [
  {
    id: 1,
    name: "iPhone 15",
    price: 7999,
    description: "最新款苹果手机",
    category: "电子产品",
    stock: 50,
    createTime: new Date("2024-01-01").toISOString(),
    updateTime: new Date("2024-01-01").toISOString(),
  },
  {
    id: 2,
    name: "MacBook Pro",
    price: 15999,
    description: "高性能笔记本电脑",
    category: "电子产品",
    stock: 30,
    createTime: new Date("2024-01-02").toISOString(),
    updateTime: new Date("2024-01-02").toISOString(),
  },
  {
    id: 3,
    name: "Nike运动鞋",
    price: 899,
    description: "舒适透气运动鞋",
    category: "服饰",
    stock: 100,
    createTime: new Date("2024-01-03").toISOString(),
    updateTime: new Date("2024-01-03").toISOString(),
  },
];

let nextId = 4;

// 商品存储操作函数
export const ProductsStore = {
  // 获取所有商品
  getAll(): Product[] {
    return [...products];
  },

  // 根据ID获取商品
  getById(id: number): Product | undefined {
    return products.find((p) => p.id === id);
  },

  // 创建新商品
  create(
    productData: Omit<Product, "id" | "createTime" | "updateTime">
  ): Product {
    const newProduct: Product = {
      ...productData,
      id: nextId++,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
    };
    products.push(newProduct);
    return newProduct;
  },

  // 更新商品
  update(id: number, productData: Partial<Product>): Product | null {
    const index = products.findIndex((p) => p.id === id);
    if (index === -1) return null;

    products[index] = {
      ...products[index],
      ...productData,
      id, // 确保ID不会被覆盖
      updateTime: new Date().toISOString(),
    };
    return products[index];
  },

  // 删除商品
  delete(id: number): Product | null {
    const index = products.findIndex((p) => p.id === id);
    if (index === -1) return null;

    const deletedProduct = products[index];
    products.splice(index, 1);
    return deletedProduct;
  },

  // 根据分类过滤
  getByCategory(category: string): Product[] {
    return products.filter((p) => p.category === category);
  },

  // 搜索商品
  search(keyword: string): Product[] {
    const lowerKeyword = keyword.toLowerCase();
    return products.filter(
      (p) =>
        p.name.toLowerCase().includes(lowerKeyword) ||
        p.description.toLowerCase().includes(lowerKeyword)
    );
  },

  // 获取所有分类
  getCategories(): { name: string; count: number }[] {
    const categories = [...new Set(products.map((p) => p.category))];
    return categories.map((category) => ({
      name: category,
      count: products.filter((p) => p.category === category).length,
    }));
  },

  // 获取库存不足的商品
  getLowStockProducts(threshold: number = 20): Product[] {
    return products.filter((p) => p.stock < threshold);
  },
};
